package com.shinbada.modules.sys.web;

import com.google.common.collect.Lists;
import com.shinbada.common.json.AjaxJson;
import com.shinbada.common.tree.TreeUtil;
import com.shinbada.core.web.BaseController;
import com.shinbada.modules.sys.entity.Menu;
import com.shinbada.modules.sys.service.MenuService;
import com.shinbada.modules.sys.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜单Controller
 *
 * @author initcap
 * @version 2016-3-23
 */

@RestController
@RequestMapping("/sys/menu")
@Api(tags = "菜单管理")
public class MenuController extends BaseController {

    @Autowired
    private MenuService menuService;

    @ModelAttribute("menu")
    public Menu get(@RequestParam(required = false) String id) {
        if (StringUtils.isNotBlank(id)) {
            return menuService.get(id);
        } else {
            return new Menu();
        }
    }

    @RequiresPermissions("user")
    @GetMapping("list")
    @ApiOperation("获取菜单集合")
    public AjaxJson list() {
        List<Menu> menus = Lists.newArrayList();
        for (Menu menu : menuService.findAllMenu()) {
            if (!"1".equals(menu.getId())) {
                menus.add(menu);
            }
        }
        return AjaxJson.success().put("menuList", menus);
    }

    @RequiresPermissions("user")
    @GetMapping("queryById")
    @ApiOperation("根据主键进行菜单查询")
    public AjaxJson queryById(Menu menu) {
        if (menu.getParent() == null || menu.getParent().getId() == null) {
            menu.setParent(new Menu(Menu.getRootId()));
        }
        menu.setParent(menuService.get(menu.getParent().getId()));
        return AjaxJson.success().put("menu", menu);
    }

    @RequiresPermissions(value = {"sys:menu:add", "sys:menu:edit"}, logical = Logical.OR)
    @PostMapping("save")
    @ApiOperation("保存菜单")
    public AjaxJson save(Menu menu) {
        if (!UserUtils.getUser().isAdmin()) {
            return AjaxJson.error("越权操作，只有超级管理员才能添加或修改数据！");
        }
        /**
         * 后台hibernate-validation插件校验
         */
        String errMsg = beanValidator(menu);
        if (StringUtils.isNotBlank(errMsg)) {
            return AjaxJson.error(errMsg);
        }

        menuService.saveMenu(menu);

        return AjaxJson.success("保存成功!");
    }

    @RequiresPermissions("sys:menu:del")
    @DeleteMapping("delete")
    @ApiOperation("删除菜单")
    public AjaxJson delete(Menu menu) {
        if (!UserUtils.getUser().isAdmin()) {
            return AjaxJson.error("越权操作，菜单不可删除！");
        }
        menuService.delete(menu);
        return AjaxJson.success("删除成功!");
    }

    @RequiresPermissions("sys:menu:updateSort")
    @PostMapping("sort")
    @ApiOperation("修改菜单排序")
    public AjaxJson sort(String id1, int sort1, String id2, int sort2) {
        if (shinProperites.isDemoMode()) {
            return AjaxJson.error("演示模式，不允许操作！");
        }
        Menu menu = new Menu();
        menu.setId(id1);
        menu.setSort(sort1);
        menuService.updateSort(menu);
        menu.setId(id2);
        menu.setSort(sort2);
        menuService.updateSort(menu);
        return AjaxJson.success("排序成功！");
    }

    @RequiresPermissions("user")
    @GetMapping("treeData")
    @ApiOperation("isShowHide是否显示隐藏菜单")
    public AjaxJson treeData(@RequestParam(required = false) String extId, @RequestParam(required = false) String isShowHide) {
        List<Menu> list = menuService.findAllMenu();
        List<Menu> filter = filterMenuByExtIdAndIsShowHide(list, extId, isShowHide);
        return AjaxJson.success().put("treeData", TreeUtil.buildLevelTreeSort(filter));

    }

    @RequiresPermissions("user")
    @GetMapping("treeData2")
    @ApiOperation("获取所有的菜单，并且不返回功能菜单这个顶级")
    public AjaxJson treeData2() {
        List<Menu> list = menuService.findAllMenu();
        return AjaxJson.success().put("treeData", TreeUtil.buildLevelTreeSort(list).get(0).getChildren());
    }

    private List<Menu> filterMenuByExtIdAndIsShowHide(List<Menu> list, String extId, String isShowHide) {
        if (StringUtils.isNotBlank(extId)) {
            list = list.stream().filter(menu -> !menu.getParentIds().contains(extId)).collect(Collectors.toList());
        }
        if (StringUtils.isNotBlank(isShowHide) && Menu.MENU_HIDE.equals(isShowHide)) {
            list = list.stream().filter(menu -> Menu.MENU_SHOW.equals(menu.getIsShow())).collect(Collectors.toList());
        }
        return list;
    }

}
